package com.hmily.dubbo.consumer.sync;

import com.hmily.dubbo.api.bean.UserInfo;
import org.apache.dubbo.common.beanutil.JavaBeanDescriptor;
import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * <h1>泛化调用 -- Bean 引用类型传参调用.</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-11-01
 */
public class GenericBeanRefConsumerApplication {

    public static void main(String[] args) throws Exception {
        // 设置应用服务名称
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-consumer");
        // 设置注册中心的地址
        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");

        // 创建引用 org.apache.dubbo.rpc.service.GenericService 这个服务的对象
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setRegistry(registryConfig);
        referenceConfig.setCheck(false);

        referenceConfig.setInterface("com.hmily.dubbo.api.UserQueryFacade");
        // referenceConfig.setGeneric(true);
        // referenceConfig.setGeneric("nativejava");
        // RpcContext.getContext().setAttachment("generic", "nativejava");
        referenceConfig.setGeneric("bean");
        RpcContext.getContext().setAttachment("generic", "bean");

        /***********************************************************/
        /** 模拟别人给过来的 json 数据并想办法转成了 UserInfo 对象，start **/
        /***********************************************************/
        UserInfo userInfo = new UserInfo();
        userInfo.setId("G314");
        userInfo.setName("hmilyylimh");
        userInfo.setSex("M");
        /***********************************************************/
        /** 模拟别人给过来的 json 数据并想办法转成了 UserInfo 对象，end   **/
        /***********************************************************/

        // 直接拿到引用的代理对象，然后进行远程调用
        JavaBeanDescriptor reqParams = JavaBeanSerializeUtil.serialize(userInfo);
        GenericService genericService = referenceConfig.get();
        Object result = genericService.$invoke("queryUserInfo",
                new String[]{"com.hmily.dubbo.api.bean.UserInfo"},
                new Object[]{reqParams});

        // 打印结果
        result = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor)result);
        System.out.println(result);

        // 阻塞等待
        System.in.read();
    }
}
